import 'package:flutter/material.dart';
import '../helpers/ensure_visible.dart';
import '../Models/product.dart';
import 'package:scoped_model/scoped_model.dart';
import '../ScopedModels/ScopedProduct.dart';

class ProductEdit extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _ProductEditState();
  }
}

class _ProductEditState extends State<ProductEdit> {


  //表单状态
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  //
  Map<String, dynamic> _formData = {
    'title': null,
    'description': null,
    'price': 0,
    'image': 'assets/food.jpg'
  };

  @override
  Widget build(BuildContext context) {
    return ScopedModelDescendant(
        builder: (BuildContext build, Widget child, ScopedProduct model) {
     
      final Widget content = _buildInputView(context, model.selectProduct);

      return model.selectIndex == null
          ? content
          : Scaffold(
              appBar: AppBar(
                title: Text('编辑'),
              ),
              body: content,
            );
    });
  }

  Widget _buildInputView(BuildContext context, Product product) {
    return GestureDetector(
       //手势回收键盘
          onTap: () {
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: Container(
        margin: EdgeInsets.all(10.0),
        child: Form(
            key: _formKey,
            child: ListView(
              children: <Widget>[
                _buildNameText(product),
                _buildDescriptionText(product),
                _buildPriceText(product),
                _buildSubmit()
              ],
            ))));
  }

  Widget _buildSubmit() {
    return ScopedModelDescendant<ScopedProduct>(
        builder: (BuildContext build, Widget child, ScopedProduct model) {
      return Container(
        padding: EdgeInsets.all(10.0),
        child: RaisedButton(
            child: Text('保存'),
            onPressed: () =>
                _submitValues(model.addProduct, model.updateProduct, model.selectProductIndex, model.selectIndex)),
      );
    });
  }

  final _titleNode = FocusNode();
  final _desNode = FocusNode();
  final _priceNode = FocusNode();
  Widget _buildNameText(Product product) {
    return EnsureVisibleWhenFocused(
        focusNode: _titleNode,
        child: TextFormField(
          initialValue: product == null ? '' : product.title,
          decoration: InputDecoration(labelText: '产品名称'),
          validator: (String value) {
            //删除首尾空格
            if (value.isEmpty || value.trim().length <= 5) {
              return '名称字数必须大于5';
            }
          },
          onSaved: (String value) {
            _formData['title'] = value;
          },
        ));
  }

  Widget _buildDescriptionText(Product product) {
    return EnsureVisibleWhenFocused(
        focusNode: _desNode,
        child: TextFormField(
          initialValue:
              product == null ? '' : product.description,
          decoration: InputDecoration(labelText: '产品描述'),
          validator: (String value) {
            if (value.isEmpty || value.trim().length <= 5) {
              return '描述字数必须大于5';
            }
          },
          onSaved: (String value) {
            _formData['description'] = value;
          },
        ));
  }

  Widget _buildPriceText(Product product) {
    return EnsureVisibleWhenFocused(
        focusNode: _priceNode,
        child: TextFormField(
          initialValue:
              product == null ? '' : product.price.toString(),
          decoration: InputDecoration(labelText: '产品价格'),
          keyboardType: TextInputType.numberWithOptions(),
          validator: (String value) {
            if (!RegExp(r'^(?:[1-9]\d*|0)?(?:\.\d+)?$').hasMatch(value)) {
              return '价格必须为数字';
            }
          },
          onSaved: (String value) {
            setState(() {
              _formData['price'] = double.parse(value);
            });
          },
        ));
  }

  _submitValues(Function addProduct, Function updateProduct,Function selectProductIndex, [int selectIndex]) {
    if (!_formKey.currentState.validate()) {
      return;
    }
    _formKey.currentState.save();
    print(_formData);
    if (selectIndex != null) {
      updateProduct(
          Product(
              title: _formData['title'],
              description: _formData['description'],
              imageURL: _formData['image'],
              price: _formData['price'],
              isFavorite: false
              ));
     
    } else {
      addProduct(Product(
          title: _formData['title'],
          description: _formData['description'],
          imageURL: _formData['image'],
          price: _formData['price'],
          isFavorite: false
          ));
           
    }
    // Navigator.pushReplacementNamed(context, '/products').then((_) => selectProductIndex(null));
   
  }
}
